<?php

namespace app\admin\controller;

use think\Request;

class permission extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $data = model('permission')->select();
        $data = collection($data)->toArray();
        $permissions = generateTree($data);
        return $this->fetch('', ['permissions' => $permissions]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        if (\request()->isPost()) {
            $data = input('post.');
            //进行自动验证
            $validate = validate('Permission');
            if (!$validate->scene('add')->check($data)) {
                $this->error($validate->getError());
            }
            //添加权限
            //根据选择的父类id定义权限等级
            if ($data['ps_pid'] != 0) {
                $pid = model('permission')->get(['ps_id' => $data['ps_pid']]);
                $data['ps_level'] = (string)($pid['ps_level'] + 1);
            } else {
                $data['ps_level'] = '0';
            }
            //数据入库
            $res = model('permission')->save($data);
            if (!$res) {
                $this->error('添加失败');
            } else {
                $this->success('添加成功');
            }
        }
        //获取所有的权限
        $data = model('permission')->select();
        $data = collection($data)->toArray();
        $permissions = generateTree($data);
        return $this->fetch('', ['permissions' => $permissions]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
